package service.impl;

import dao.OrderDao;
import dao.impl.OrderDaoimpl;
import pojo.Order;
import pojo.OrderItem;
import pojo.PageBean;
import pojo.User;
import service.OrderService;
import utils.JdbcUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.10 下午 14:04
 */
public class OrderServiceimpl implements OrderService {
    @Override
    public void addOrder(Order order) {
        try {
            JdbcUtils.startTransacton();//开启事务
            OrderDao orderDao = new OrderDaoimpl();
            orderDao.insertOrder(order);

            //订单--获取所有的订单项
            List<OrderItem> items = order.getItems();
            for (OrderItem orderItem : items) {
                orderDao.insertOrderItem(orderItem);
            }
            //提交事务
            JdbcUtils.commitAndClose();

        } catch (SQLException e) {
            e.printStackTrace();
            try {
                JdbcUtils.rollbackAndClose();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

    }

    @Override
    public PageBean<Order> getOrderbyPage(int currentPage, int pageSize, User user) {
        try {
            OrderDao orderDao = new OrderDaoimpl();
            List<Order> list = orderDao.OrderbyPage(currentPage,pageSize,user);
            int totalCount = orderDao.selecttotalCount();
            return new PageBean<Order>(currentPage,pageSize,totalCount,list);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Order getById(String oid) {
        try {
            OrderDao orderDao = new OrderDaoimpl();
            return orderDao.selectOrderById(oid);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 更新订单
     * @param order
     */
    @Override
    public void update(Order order) {
        try {
            OrderDao orderDao = new OrderDaoimpl();
            orderDao.update(order);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
